package com.appinfo.service;

import com.appinfo.mapper.AppVersionMapper;
import com.appinfo.pojo.AppVersion;
import com.appinfo.pojo.DevUser;
import com.appinfo.vo.AppVersionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppVersionServiceImpl implements AppVersionService{
    //app状态码
    private static final String STATUSCODE = "PUBLISH_STATUS";

    @Autowired
    private AppVersionMapper appVersionMapper;
    @Autowired
    private AppService appService;
    @Autowired
    private DataDictionaryService dataDictionaryService;


    @Override
    public List<AppVersionVo> queryVersionListById(Long id) {
        List<AppVersion> appVersions = appVersionMapper.queryVersionListById(id);
        if(CollectionUtils.isEmpty(appVersions)){
            return null;
        }

        String softwareName = appService.querySoftwareNameById(id);
        List<AppVersionVo> appVersionVos = appVersions.stream().map(appVersion -> {
            AppVersionVo appVersionVo = new AppVersionVo();
            BeanUtils.copyProperties(appVersion,appVersionVo);

            //补全属性
            appVersionVo.setAppName(softwareName);
            appVersionVo.setPublishStatusName(dataDictionaryService.queryAppDataDicName(STATUSCODE,appVersion.getPublishStatus()));

            return appVersionVo;
        }).collect(Collectors.toList());
        return appVersionVos;
    }

    @Override
    @Transactional
    public void saveAppVersion(AppVersion appVersion, DevUser devUser) {
        Long devId = devUser.getId();
        //补全属性
        appVersion.setCreatedBy(devId);
        appVersion.setModifyBy(devId);
        appVersion.setCreationDate(new Date());
        appVersion.setModifyDate(new Date());
        //保存版本信息
        appVersionMapper.saveAppVersion(appVersion);

        //更新info表的版本信息
        appService.updateAppInfoVersionById(appVersion.getId(),appVersion.getAppId());

    }

    /**
     * 通过版本id查询版本信息
     * @param vid
     * @return
     */
    @Override
    public AppVersion queryVersionByVid(Long vid) {
        AppVersion appVersion = appVersionMapper.queryVersionByVid(vid);
        return appVersion;
    }

    /**
     * 更新version版本信息
     * @param appVersion
     */
    @Override
    public void updateVersion(AppVersion appVersion,DevUser devUser) {
        appVersion.setModifyBy(devUser.getId());
        appVersion.setModifyDate(new Date());
        appVersionMapper.updateVersion(appVersion);
    }

    @Override
    public void delAppApkById(Long id) {
        appVersionMapper.delAppApkById(id);
    }

}
